<?php
/** [广告表逻辑层模型]
 * @Author: 976123967@qq.com
 * @Date:   2015-01-16 11:33:22
 * @Last Modified by:   Administrator
 * @Last Modified time: 2015-03-11 15:15:18
 */
class AdLogic extends Model{

	// 表名称
	protected $tableName = 'ad';


	// 自动验证
    // array(验证字段,验证规则,错误提示,[验证条件,附加规则,验证时间])
    protected $_validate=array(
    	//广告位置
    	array('position_psid','/^[^0]\d*$/','请选择广告位置',1,'regex',3),  
        // 广告名称验证
        array('name','require','广告名称必须填写',1),
     	array('sort','require','请输入排序值',1,'regex',3),
		array('sort','/^\d+$/i','排序值只能是数字',1,'regex',3),
    );

    // 自动完成
    protected $_auto = array (
        // 时间转成时间戳
        array('addtime','time',1,'function'), 
        // 管理员aid
        array('user_uid','_uid',1,'callback'),
    );

    // 用户uid
	public function _uid()
	{
		return session('uid');
	}



	/**
	 * [get_all 读取广告]
	 * @return [type] [description]
	 */
	public function get_all()
	{
		// 开始时间
		$beginTime  	= I('get.search_begin_time','');  
		// 结束时间
		$endTime    	= I('get.search_end_time','');
		// 位置
		$psid			= I('get.psid',0,'intval');
		// 关键词
		$searchKeyword  = I('get.search_keyword','');
		// 审核状态
		$state 			= I('get.state',0,'intval');

		// 更具初始化数据设置GET
		if(!$beginTime)
			$_GET['search_begin_time'] = '';
		if(!$endTime)
			$_GET['search_end_time'] = '';
		if(!$psid)
			$_GET['psid'] = 0;
		if(!$searchKeyword)
			$_GET['search_keyword'] = '';	
		if(!$state)
			$_GET['state'] = 2;	

		// 设置where
		$where  = null;


		// 开始时间
		if($beginTime)
			$where['addtime']        = strtotime($beginTime);
		// 结束时间
		if($endTime)
			$where['addtime']        = strtotime($endTime)+24*60*60;
		// 位置
		if($psid)
			$where['position_psid']  = $psid;

		// 广告名称关键词查找
		if($searchKeyword )
			$where[] 				 = "name like '%{$searchKeyword}%'";


		// 审核状态
		switch ($_GET['state']) 
		{
			case 1:
				$where['verifystate']   = 1;
				break;
			case 2:
				$where['verifystate']   = 2;
				break;
		}

		$adViewModel = D('AdView');

		import('ORG.Util.Page');// 导入分页类
		$count = $adViewModel->where($where)->count();



		// 没有数据
		if(!$count)
			return false;
		// 分页
		$page  = new Page($count,20);

		// 字段
		$field ='sort,verifystate,aid,position_psid,position_name,name,username,addtime,pic';

		// 排序
		$order = 'ad.sort asc ,aid desc';
		// limit
		$limit = $page->firstRow.','.$page->listRows;
		// 读取数据
		$data  = $adViewModel->where($where)->limit($limit)->order($order)->field($field)->select();
		// 处理数据
		foreach ($data as $k=>$v)
		{

			$data[$k]['verifystate'] = $v['verifystate']==1?'审核中':($v['verifystate']==2?'审核通过':'审核失败');
			
			// 发布时间
			$data[$k]['time']        = $v['addtime'];
			$data[$k]['addtime']     = date('Y-m-d',$v['addtime']);

			// 图片
			$data[$k]['pic']= $v['pic']?__ROOT__.'/'.$v['pic']:__ROOT__.'/Data/Public/images/default.gif';

		}
		// 分页样式更改
		$page->setConfig('theme','<span>%totalRow% %header% %nowPage%/%totalPage% 页 </span>%upPage% %downPage% %first% %prePage% %linkPage% %nextPage% %end%');

		// 页脚信息
		$data['page'] = $page->show();


		return $data;
	}


	/**
	 * [add_ad 添加广告]
	 */
	public function add_ad()
	{
		
		// 验证
		if(!$this->create())
			return false;
		$data = $this->data;
		// 图片上传
		$pic  = $this->alter_pic();
		if($pic === false)
			return false;
		$data['pic'] = $pic;

		// 执行添加
		$this->add($data);

		return  true;
	}

	/**
		 * [alter_pic 上传图片]
		 * @return [type] [description]
		 */
		public function alter_pic()
		{

			$aid = I('post.aid');
			if($aid&&!empty($_FILES['pic']['name']))
			{
				$field = $this->where(array('aid'=>$aid))->find();
				is_file($field['pic']) and unlink($field['pic']);
			}

			if(!empty($_FILES['pic']['name']))
			{
				// 上传类
				import('ORG.Net.UploadFile');
				$upload = new UploadFile();// 实例化上传类
				$upload->maxSize  = 3145728 ;// 设置附件上传大小

	            $ext = explode('|', C('cfg_image'));
            	$upload->allowExts  = $ext;// 设置附件上传类型
	            $savePath = './Data/Uploads/image/'.date('Y').'/'.date('m').'/'.date('d').'/';
	            // 创建目录
	            is_dir($savePath) || mkdir($savePath,0777,true);
	            // 执行上传
	            if($info=$upload->uploadOne($_FILES['pic'],$savePath))
	                return $info[0]['savepath'].$info[0]['savename'];
	            else
	            {
	            	$this->error=$upload->getError();
	            	return false;
	            }

			}
			else
				return '';
		}

		/**
		 * [find_one 读取一条数据]
		 * @return [type] [description]
		 */
		public  function find_one()
		{
			$aid = I('get.aid');
			$data = $this->where(array('aid'=>$aid))->find();
			if(!$data)
			{
				$this->error ='链接错误';
				return false;
			}

			$data['has_pic'] = $data['pic']?true:false;
			// 图片
			$data['pic']= $data['pic']?__ROOT__.'/'.$data['pic']:__ROOT__.'/Data/Public/images/default.gif';

			return $data;
		}

		/**
		 * [update_ad 更新广告]
		 * @return [type] [description]
		 */
		public function update_ad()
		{
			// 验证
			if(!$this->create())
				return false;
			$data = $this->data;
			// 图片上传
			$pic  = $this->alter_pic();
			if($pic === false)
				return false;
			if($pic!='')
				$data['pic'] = $pic;

			// 执行更新
			$this->save($data);


			return  true;
		}


		/**
		 * [del 删除 获取 aid]
		 * @return [type] [description]
		 */
		public function del_ad()
		{
			$aid = I('get.aid');
			$this->del_ad_by_aid($aid);
			return true;
		}

		/**
		 * [del 删除]
		 * @return [type] [description]
		 */
		public function del_ad_by_aid($aid)
		{
			$field = $this->where(array('aid'=>$aid))->find();
			if(!$field)
				return false;
			is_file($field['pic']) && unlink($field['pic']);
			// 删除广告
			$this->delete($aid);
		}



		/**
		 * [operation 批量操作]
		 * @return [type] [description]
		 */
		public function operation()
		{
			$aid  = I('post.aid');
			switch (true) 
			{
				// 排序
				case isset($_POST['update_sort']): 
					$sort = I('post.sort');
					foreach($aid as $k=>$v)
					{
						$this->save(array('sort'=>$sort[$k],'aid'=>$v));
					}
					$msg= '广告排序成功';
					break;
				
				// 删除
				case isset($_POST['update_del']):
					foreach($aid as $k=>$v)
					{
						$this->del_ad_by_aid($v);	
					}
					$msg= '广告删除成功';
				break;

				// 审核通过
				case isset($_POST['update_check_state']): 
					$sort = I('post.sort');
					foreach($aid as $k=>$v)
					{
						$this->save(array('verifystate'=>2,'aid'=>$v));
					}
					$msg= '广告审核成功';
					break;
				// 取消审核
				case isset($_POST['update_cancle_state']): 
					$sort = I('post.sort');
					foreach($aid as $k=>$v)
					{
						$this->save(array('verifystate'=>1,'aid'=>$v));
					}
					$msg= '广告取消审核成功';
					break;

				default:
					$this->error = '操作选择错误';
					return false;
			}

			return $msg;
		}


}